using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Extensions.DependencyInjection;

namespace DocumentCreationSystem.Views
{
    public partial class RWKVModelManagerWindow
    {
        private async void StartLocalForRow_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (ModelsGrid.SelectedItem is not RWKVModelManagerWindow.RowVM row) return;

                // 解析模型路径（文件或目录）
                string modelPath = row.FullPath ?? System.IO.Path.Combine(ModelDirTextBox.Text.Trim(), row.name);
                if (!File.Exists(modelPath))
                {
                    var dirTry = System.IO.Path.Combine(ModelDirTextBox.Text.Trim(), System.IO.Path.GetFileNameWithoutExtension(row.name));
                    if (Directory.Exists(dirTry)) modelPath = dirTry;
                }

                // 直接启用内置本地推理（移除外部 Runner 方式）
                var cfgSvc = App.ServiceProvider.GetRequiredService<DocumentCreationSystem.Models.IAIModelConfigService>();
                var cfg = await cfgSvc.GetConfigAsync();
                cfg.Platform = "RWKV";
                cfg.RWKVConfig.SelectedModel = row.name;
                cfg.RWKVConfig.LocalModeEnabled = true;
                cfg.RWKVConfig.LocalBackendType = string.IsNullOrWhiteSpace(cfg.RWKVConfig.LocalBackendType) ? "onnx" : cfg.RWKVConfig.LocalBackendType;
                cfg.RWKVConfig.LocalModelPath = modelPath;
                await cfgSvc.SaveConfigAsync(cfg);

                // 尝试自动定位 tokenizer（非阻塞）
                try
                {
                    var tokSvc = App.ServiceProvider.GetService(typeof(DocumentCreationSystem.Services.ITokenizerLocatorService)) as DocumentCreationSystem.Services.ITokenizerLocatorService;
                    if (tokSvc != null)
                    {
                        var tok = await tokSvc.EnsureTokenizerAsync(cfg.RWKVConfig, modelPath);
                        if (!string.IsNullOrWhiteSpace(tok))
                        {
                            await cfgSvc.SaveConfigAsync(cfg); // 回写 LocalTokenizerPath
                        }
                    }
                }
                catch { }

                if (App.ServiceProvider.GetService<DocumentCreationSystem.Services.IAIService>() is DocumentCreationSystem.Services.AIServiceManager aiMgr)
                {
                    await aiMgr.ReloadConfigurationAsync();
                }

                StatusText.Text = "已启用本地推理（进程内，无需外部 Runner）";
            }
            catch (Exception ex)
            {
                StatusText.Text = "启用本地推理失败: " + ex.Message;
            }
        }
    }
}

